<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button v-if="!isOrderTaker" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['enterprise:workOrder:add']"
        >创建预约看房
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="工单编号" prop="workOrderId">
        <el-input v-model="queryParams.workOrderId" placeholder="请输入工单编号" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 240px"
                        value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="预约人" prop="contactsName">
        <el-input v-model="queryParams.contactsName" placeholder="请输入姓名" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.contactsPhone" placeholder="请输入手机" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房源" prop="premisesAddress">
        <el-input v-model="queryParams.premisesAddress" placeholder="搜索小区、单元、门牌号" clearable
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="带看员" prop="personName">
        <el-input v-model="queryParams.personName" placeholder="请输入带看员姓名" clearable
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="评价" prop="estimationFlag">
        <el-select v-model="queryParams.estimationFlag" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="item in commentStatusList" :key="item.value" :label="item.label" :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!-- 导出-->
        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部" name=""></el-tab-pane>
      <el-tab-pane :label="'待派单('+statistics['1']+')'" name="wait"></el-tab-pane>
      <el-tab-pane :label="'待接单('+statistics['2']+')'" name="receiving"></el-tab-pane>
      <el-tab-pane :label="'已接单('+statistics['3']+')'" name="accept"></el-tab-pane>
<!--      <el-tab-pane :label="'维修中('+statistics['4']+')'" name="repair"></el-tab-pane>-->
<!--      <el-tab-pane :label="'待缴费('+statistics['5']+')'" name="pay"></el-tab-pane>-->
      <el-tab-pane :label="'已完成('+statistics['6']+')'" name="finish"></el-tab-pane>
      <el-tab-pane :label="'已取消('+statistics['7']+')'" name="cancel"></el-tab-pane>
      <el-tab-pane :label="'待审核('+statistics['8']+')'" name="audit"></el-tab-pane>
<!--      <el-tab-pane :label="'已超时('+statistics['timeoutFlag']+')'" name="timeout"></el-tab-pane>-->
    </el-tabs>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelect">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column width="55" label="序号" align="center" key="lockName" prop="lockName"
                       :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="工单编号" align="center" prop="workOrderId" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.workOrderId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单来源" align="center" prop="workOrderSource" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_order_source" :value="scope.row.workOrderSource"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="房源" align="center" prop="premisesAddress" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.premisesAddress">{{ scope.row.premisesAddress }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyDate" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime|formatDate('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约人" align="center" prop="contactsName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.contactsName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="contactsPhone" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.contactsPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.appointmentTime">{{ scope.row.appointmentTime }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="期望入住时间" align="center" prop="expectCheckInType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.expect_check_in_type" :value="scope.row.expectCheckInType"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="指定带看员" align="center" prop="busUserId" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.expectPersonName ? scope.row.expectPersonName : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.workOrderRemark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="带看员" align="center" prop="busUserId" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div>
            <div>{{ scope.row.personName }}</div>
            <div>{{ scope.row.personPhone }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="工单状态" align="center" prop="workOrderState" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.work_order_state"
            :value="scope.row.workOrderState"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />
    <!--  添加维修员弹出层   -->
    <Add v-model="open" :title="title" @success="handleRefresh"/>
    <!--  详情弹出层   -->
    <Detail v-model="detailVisible" :title="title" :data="form" :isOrderTaker="isOrderTaker" @success="handleRefresh"/>
  </div>
</template>

<script>
import Add from './components/add.vue'
import Detail from './components/detail.vue'
import { debounce } from '@/utils'
import {
  listWorkOrder,
  countWorkOrderState,
  exportWorkOrder,
  listWorkOrderByMaintenance
} from '@/api/houseManagement/workOrder'
import { getMaintenanceItemInfo } from '@/api/houseManagement/maintenanceItem'

export default {
  name: 'Index',
  dicts: ['work_order_state', 'maintenance_type','expect_check_in_type','work_order_source'],
  components: {
    Add,
    Detail
  },
  props: {
    // 是否是订单承接人
    isOrderTaker: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 选中项
      activeName: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 详情弹出层是否显示
      detailVisible: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params: {
          itemId: null, //项目id
          beginTime: null, //开始时间
          endTime: null //结束时间
        },
        workOrderId: null, //工单编号
        contactsName: null, //报修人姓名
        contactsPhone: null, //报修人手机号
        premisesAddress: null, //报修人地址
        busUserId: null, //维修员的账号id
        maintenanceType: null,//维修类型(1.个人维修,2.公共维修)
        estimationFlag: null, //是否评价(0.否,1.是)
        workOrderState: null, //工单状态(1.待派单,2.待接单,3.已接单,4.维修中,5.待缴费,6.已完成,7.已取消,8.待审核)
        workOrderType: '1' //工单类型(1.维修工单,2.保洁工单,3.带看工单)
      },
      // 统计数据
      statistics: {
        '1': 0, //待派单
        '2': 0,//待接单
        '3': 0,//已接单
        '4': 0,//维修中
        '5': 0,//待缴费
        '6': 0,//已完成
        '7': 0,//已取消
        '8': 0,//待审核
        'timeoutFlag': 0//已超时
      },
      stateMapping: {
        wait: '1',
        receiving: '2',
        accept: '3',
        repair: '4',
        pay: '5',
        finish: '6',
        cancel: '7',
        audit: '8',
        timeout: 'timeoutFlag'
      },
      // 项目列表
      projectList: [],
      // 评价状态列表
      commentStatusList: [
        {
          value: 1,
          label: '已评价'
        },
        {
          value: 2,
          label: '未评价'
        }
      ]
    }
  },
  computed: {
    //故障图片列表
    faultPictureList() {
      return (value) => {
        return value ? value.split(',') : []
      }
    },
    itemNames() {
      return (value) => {
        let list = value ? value.map(item => item.itemName) : []
        return list.join(' | ')
      }
    }
  },
  watch: {},
  created() {
    this.initData()

  },
  methods: {
    /** 初始化数据 */
    initData() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        params: {
          itemId: null, //项目id
          beginTime: null, //开始时间
          endTime: null //结束时间
        },
        workOrderId: null, //工单编号
        contactsName: null, //报修人姓名
        contactsPhone: null, //报修人手机号
        premisesAddress: null, //报修人地址
        busUserId: null, //维修员的账号id
        maintenanceType: null,//维修类型(1.个人维修,2.公共维修)
        estimationFlag: null, //是否评价(0.否,1.是)
        workOrderState: null, //工单状态(1.待派单,2.待接单,3.已接单,4.维修中,5.待缴费,6.已完成,7.已取消,8.待审核)
        workOrderType: '3' //工单类型(1.维修工单,2.保洁工单,3.带看工单)
      }
      this.handleQuery()
      this.getProjectList()
    },
    getProjectList() {
      getMaintenanceItemInfo().then(response => {
        this.projectList = response.data.map(item => {
          return {
            label: item.maintenanceItemName,
            value: item.maintenanceItemId
          }
        })
      })
    },
    // 选项改变
    handleClick(tab, event) {
      console.log('tab', tab)
      if (tab.name == 'timeout') {
        this.queryParams['timeoutFlag'] = '1'
        this.queryParams.workOrderState = null
      } else {
        this.queryParams['timeoutFlag'] = null
        this.queryParams.workOrderState = this.stateMapping[tab.name]
      }
      this.handleQuery()
    },
    // 选中项
    handleSelect(selection) {
      console.log('selection', selection)
      this.ids = selection.map(item => item.workOrderId)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      let apiUrl = ''
      if (this.isOrderTaker) {
        apiUrl = listWorkOrderByMaintenance
        this.queryParams['searchValue'] = 1
      } else {
        apiUrl = listWorkOrder
        this.queryParams['searchValue'] = undefined
      }

      apiUrl(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 统计数据 */
    getStatistics() {
      let params = {
        workOrderType: this.queryParams.workOrderType,
      }
      if (this.isOrderTaker) {
        params['searchValue'] = '1'
      }
      countWorkOrderState(params).then(res => {
        console.log('countWorkOrderState', res)
        res.data.forEach(item => {
          this.statistics[item.workOrderState] = item.num
        })
      })
    },
    // 刷新
    handleRefresh() {
      this.getList()
      this.getStatistics()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      this.getStatistics()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.title = '预约看房申请'
    },
    handleDetail(row) {
      console.log('row', row)
      this.form = { ...row }
      this.detailVisible = true
      this.title = '工单详情'
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log('handleExport', this.ids)
      let params = { ...this.queryParams, workOrderIds: this.ids }
      this.download('/enterprise/workOrder/workOrder/export', {
        ...params
      }, `看房工单_${new Date().getTime()}.xlsx`)
    }

  }
}
</script>

<style lang="scss" scoped></style>
